﻿using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using Learun.Util;
using Learun.Util.SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-06-21 15:32
    /// 描 述：关联类型表
    /// </summary>
    public class ec_CableBLL
    {
        ec_CableService ec_CableService;
        ec_CableSetService ec_CableSetService;
        ec_CableSetWireService ec_CableSetWireService;
        ec_WireTerminalService ec_WireTerminalService;
        public ec_CableBLL()
        {
            ec_CableService = new ec_CableService();
            ec_CableSetService = new ec_CableSetService();
            ec_CableSetWireService = new ec_CableSetWireService();
            ec_WireTerminalService = new ec_WireTerminalService();
        }
        #region 获取数据
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IEnumerable<ec_CableEntity> GetCables(string ProjID, bool homerun = true)
        {
            var signalTable = ProjectSugar.TableName<ec_Wire_GroupEntity>(ProjID);
            var allSignals = SqlSugarHelper.Db.Queryable<ec_Wire_GroupEntity>().AS(signalTable)
                .Where(x => x.CommunicationPoint == true)
                .ToList();
            var res = ec_CableService.GetList("{ProjectId:\"" + ProjID + "\"}");
            if (homerun)
            {
                res = res.Where(x => x.CableClass == "homerun");
                foreach (var homerunCable in res)
                {
                    homerunCable.WireGroups = allSignals.Where(x => x.CableId == homerunCable.CableID).OrderBy(X => X.Group_Name);
                    homerunCable.WireGroupIds = homerunCable.WireGroups.Select(x => x.Wire_Group_ID).ToList();
                }
            }
            return res;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ec_CableEntity GetCableByEngID(string ProjID, string EngineerDataID, bool OnlySelf = false)
        {
            try
            {
                var engineerDataServ = new ec_enginedataService();
                var panelServ = new ec_PanelService();
                var panelStripBll = new ec_PanelStripBLL();
                var panelStripServ = new ec_PanelStripService();
                var termServ = new ec_PanelStripTermBLL();
                var channelServ = new ec_PanelChannelService();

                var ProjectEntity = new ec_projectEntity();
                ProjectEntity = new ec_projectService().GetEntity(ProjID);
                if (ProjectEntity == null)
                {
                    return null;
                }

                var res = ec_CableService.GetList("{ProjectId:\"" + ProjID + "\",EngineerDataID:\"" + EngineerDataID + "\"}").FirstOrDefault(); //电缆
                if (!OnlySelf && res != null)
                {
                    var sets = ec_CableSetService.GetList(ProjID, res.CableID);
                    var allWires = ec_CableSetWireService.GetList(ProjID, res.CableID, "");
                    var allConns = ec_WireTerminalService.GetList("{ProjectId:\"" + ProjID + "\",CableID:\"" + res.CableID + "\"}").ToList();

                    foreach (var set in sets)
                    {
                        var wires = allWires.Where(x => x.CableSetID == set.CableSetID);
                        #region 只针对IO模块
                        var conns = allConns.Where(x => x.CableSetID == set.CableSetID).ToList();
                        if (conns == null || conns.Count() == 0)
                        {
                            set.IsConned = false;
                        }
                        else
                        {
                            set.IsConned = true;
                            var Term = termServ.GetList("{ProjectId:\"" + ProjID + "\",TermID:\"" + conns[0].TermID + "\"}").FirstOrDefault();
                            var stripObj = panelStripServ.GetEntity(ProjID, Term?.StripID);
                            var channelObj = channelServ.GetEntity(ProjID, Term?.ChannelID);
                            var panelObj = panelServ.GetEntity(ProjID, stripObj?.PanelID);
                            var engineerDataObj = engineerDataServ.GetEntity(panelObj?.EngineerDataID, ProjID);
                            set.ConnectionInfo = $"采集箱：{engineerDataObj?.TagNumber}/模块(端子排)：{stripObj?.StripName}/通道：{channelObj?.ChannelName}";


                            //24 03 04
                            foreach (var wire in wires)
                            {
                                wire.ConnectionOnSide1 = conns.FirstOrDefault(x => x.WireID == wire.WireID && x.Cable_Side == 0);
                                wire.ConnectionOnSide2 = conns.FirstOrDefault(x => x.WireID == wire.WireID && x.Cable_Side == 1);
                            }
                        }
                        #endregion
                        set.Wires = wires.ToList();
                    }
                    res.Sets = sets.ToList();

                    #region from/to
                    var relTypeTableName = ProjectSugar.TableName<ec_reltypeEntity>(ProjID);
                    var relTableName = ProjectSugar.TableName<ec_enginedata_relEntity>(ProjID);
                    var enginedataTableName = ProjectSugar.TableName<ec_enginedataEntity>(ProjID);
                    var panelTableName = ProjectSugar.TableName<ec_PanelEntity>(ProjID);
                    var panelStripTableName = ProjectSugar.TableName<ec_PanelStripEntity>(ProjID);

                    var cableFromToRel = SqlSugarHelper.Db.Queryable<ec_reltypeEntity>().AS(relTypeTableName).First(x => x.RelType == ((int)enum_RelType.设备_电缆).ToString());
                    if (cableFromToRel == null)
                    {
                        throw new Exception($"查不到【{enum_RelType.设备_电缆.ToString()}】这个关联类型。");
                    }
                    var relDatas = SqlSugarHelper.Db.Queryable<ec_enginedata_relEntity>().AS(relTableName)
                        .Where(x => x.RelTypeID == cableFromToRel.RelTypeID && (x.RelEngineData1ID == EngineerDataID || x.RelEngineData2ID == EngineerDataID)).ToList();
                    try
                    {
                        var FromEngId = relDatas.FirstOrDefault(x => x.RelEngineData2ID == EngineerDataID)?.RelEngineData1ID;
                        res.FromPanel = panelServ.GetEntity(ProjID, FromEngId);
                        if (res.FromPanel != null)
                        {
                            res.FromPanel.strips = panelStripBll.GetList("{ProjectId:\"" + ProjID + "\",PanelID:\"" + res.FromPanel.PanelID + "\",OnlySelf:\"" + true + "\"}").ToList();
                        }

                        var ToEngId = relDatas.FirstOrDefault(x => x.RelEngineData1ID == EngineerDataID)?.RelEngineData2ID;
                        res.ToPanel = panelServ.GetEntity(ProjID, ToEngId);
                        if (res.ToPanel != null)
                        {
                            res.ToPanel.strips = panelStripBll.GetList("{ProjectId:\"" + ProjID + "\",PanelID:\"" + res.ToPanel.PanelID + "\",OnlySelf:\"" + true + "\"}").ToList();
                        }
                    }
                    catch (Exception)
                    { 
                    }

                    #endregion

                }

                return res;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

        #region 提交数据
        public void DeleteEntity(string ProjectId, string CableID)
        {
            var conns = ec_WireTerminalService.GetList("{ProjectId:\"" + ProjectId + "\",CableID:\"" + CableID + "\"}");

            if (conns != null && conns.Count() > 0)
            {
                throw new Exception("当前电缆还留有连接关系，无法执行删除。");
            }
            else { ec_CableService.DeleteEntity(ProjectId, CableID); }

        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string ProjectId, string CableID, ec_CableEntity entity)
        {
            try
            {
                if (entity != null)
                {
                    //if (!string.IsNullOrEmpty(CableID))
                    //{
                    //    ec_CableService.SaveEntity(ProjectId, CableID, entity, out CableID);
                    //}
                    //else
                    //{
                    #region New
                    //1.New Cable
                    var NewCableID = "";
                    #region  1.1 ,2023 11 30增加对其下信号的关联
                    if (entity.WireGroupIds != null && !string.IsNullOrEmpty(CableID))
                    {
                        var signalTableName = ProjectSugar.TableName<ec_Wire_GroupEntity>(ProjectId);
                        var existSignal = SqlSugarHelper.Db.Queryable<ec_Wire_GroupEntity>().AS(signalTableName)
                            .Where(c => c.CableId == CableID).Select(x => x.Wire_Group_ID)
                            .ToList();
                        SqlSugarHelper.Db.Updateable<ec_Wire_GroupEntity>().AS(signalTableName)
                            .SetColumnsIF(!string.IsNullOrEmpty(CableID), x => x.CableId == CableID)
                             .SetColumnsIF(!string.IsNullOrEmpty(CableID), x => x.Status == WireGroupStatusEnum.Used)
                            .Where(x => entity.WireGroupIds.Contains(x.Wire_Group_ID) && x.CommunicationPoint == true
                            && x.Status != WireGroupStatusEnum.Confirmed).ExecuteCommand();//符合通讯点，id又在这个电缆下的信号

                        var NeedClear = existSignal.Where(x => !entity.WireGroupIds.Contains(x)).ToList();

                        SqlSugarHelper.Db.Updateable<ec_Wire_GroupEntity>().AS(signalTableName)
                           .SetColumnsIF(!string.IsNullOrEmpty(CableID), x => x.CableId == "")
                            .SetColumnsIF(!string.IsNullOrEmpty(CableID), x => x.Status == WireGroupStatusEnum.New)
                           .Where(x => NeedClear.Contains(x.Wire_Group_ID) && x.CommunicationPoint == true
                           && x.Status != WireGroupStatusEnum.Confirmed).ExecuteCommand();//符合通讯点，id又在这个电缆下的信号

                        //原本是1234
                        //来的是3456
                        //结果是3456
                    }

                    #endregion

                    ec_CableService.SaveEntity(ProjectId, CableID, entity, out NewCableID);
                    //2.New N x Set
                    var Sets = entity.Sets;
                    if (Sets != null)
                    {
                        foreach (ec_CableSetEntity set in Sets)
                        {
                            set.CableID = NewCableID;
                            var NewSetID = "";
                            if (!set.DeleteFlg)
                            {
                                ec_CableSetService.SaveEntity(ProjectId, set.CableSetID, set, out NewSetID);
                                //3.New N x Wire
                                var Wires = set.Wires;
                                if (Wires != null)
                                {
                                    foreach (ec_CableSetWireEntity Wire in Wires)
                                    {
                                        if (!Wire.DeleteFlg)
                                        {
                                            //Wire.CableID = NewCableID;
                                            Wire.CableSetID = NewSetID;
                                            ec_CableSetWireService.SaveEntity(ProjectId, Wire.WireID, Wire);
                                        }
                                        if (Wire.DeleteFlg && !string.IsNullOrEmpty(Wire.WireID))
                                        {
                                            ec_CableSetWireService.DeleteEntity(ProjectId, Wire.WireID);
                                        }
                                    }
                                }
                            }
                            if (set.DeleteFlg && !string.IsNullOrEmpty(set.CableSetID))
                            {
                                ec_CableSetService.DeleteEntity(ProjectId, set.CableSetID);
                            }
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

    }
}
